<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\common\model\Admin;
use app\common\model\Role as RoleMoel;
use app\common\model\Node;
use think\Request;
use tree\Tree;

class Role extends AdminBase
{
    /**
     * 用户列表显示
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function admin()
    {
        $get= $_GET;
        unset($get['/admin/role/admin_html']);
        $where=[];
        if (isset($get['username'])&&!empty($get['username'])){
            $where['a.username']=['like','%'.$get['username'].'%'];
        }

        $adminModel = new Admin();
        $adminData = $adminModel
            ->alias('a')
            ->join('role r','a.role_id=r.role_id')
            ->where($where)
            ->field('a.*,r.role_name')
            ->paginate('15');
        $this->assign('adminData', $adminData);
        return $this->fetch();
    }

    /**
     * 用户添加
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function adminadd(){
        if (\request()->isGet()){
            $roleModel = new RoleMoel();
            $roleData = $roleModel->select();
            $this->assign('roleData',$roleData);
            return $this->fetch();
        }
        if (\request()->isAjax()){
            $post = input('post.');
            $validate = validate('Admin');
            if (!$validate->scene('add')->check($post)){
                return $this->resMessage(0,$validate->getError());
            }
            $adminModel = new Admin();
            $oldData = $adminModel->where('username',$post['username'])->find();
            if ($oldData!=null){
                return $this->resMessage(0,'用户已经存在！');
            }
            $data =[
                'username'=>$post['username'],
                'password'=>get_md5_str($post['pass']),
                'role_id'=>$post['role'],
                'create_time'=>time(),
            ];
            $res = $adminModel->save($data);
            if ($res){
                return $this->resMessage(1,'添加成功！');
            }else{
                return $this->resMessage(0,'添加失败！');
            }
        }

    }

    /**
     * 用户的编辑载入页面和修改数据操作
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function adminedit()
    {
        $adminModel= new Admin();
        if (\request()->isGet()){
            if (input('?param.id')){
                $id = input('param.id');

                $adminData = $adminModel->where('admin_id',$id)->find();
                $this->assign('adminData',$adminData);
                $roleModel = new RoleMoel();
                $roleData = $roleModel->select();
                $this->assign('roleData',$roleData);
                return $this->fetch();
            }else{
                abort(404);
            }

        }
        if (\request()->isAjax()){
            $post = input('post.');
            $validate = validate('Admin');
            if (!$validate->scene('edit')->check($post)){
                return $this->resMessage(0,$validate->getError());
            }
            if (!empty($post['pass'])){
                $validate = validate('Admin');
                if (!$validate->scene('add')->check($post)){
                    return $this->resMessage(0,$validate->getError());
                }
                $password = get_md5_str($post['pass']);
            }

            $id = $post['id'];
            $oldData = $adminModel->where('admin_id',$id)->find();
            if ($oldData!=null){
                $data = [
                    'username'=>$post['username'],
                    'role_id'=>$post['role'],
                ];
                if (isset($password)){
                    $data['password']=$password;
                }
                $res = $adminModel->save($data,['admin_id'=>$id]);
                if ($res){
                    return $this->resMessage(1,'修改成功');
                }else{
                    return $this->resMessage(0,'修改失败');
                }
            }else{
                return $this->resMessage(0,'出错了');
            }
        }
    }

    /**
     * 更改用户状态
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */

    public function upadminsta(){
        if (\request()->isAjax()){
            if (input('?post.id')&&input('?post.sta')){
                $id = input('post.id');
                $sta = input('post.sta');
                $adminModel = new Admin();
                $oldData = $adminModel->where('admin_id',$id)->find();
                if ($oldData!=null){
                    if ($oldData['username']!='admin'){
                        $data = ['status'=>!$sta];
                        $res = $adminModel->save($data,['admin_id'=>$id]);
                        if ($res){
                            return $this->resMessage(1,'修改成功！');
                        }else{
                            return $this->resMessage(0,'修改失败！');
                        }
                    }else{
                        return $this->resMessage(0,'admin为网站创建者不能更改状态！');
                    }

                }else{
                    return $this->resMessage(0,'出错了！');
                }
            }else{
                return $this->resMessage(0,'缺少参数！');
            }
        }else{
            abort(404);
        }
    }

    /**
     * 用户删除
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function admindel(){
        if (\request()->isAjax()){
            if (input('?post.id')){
                $id = input('post.id');
                    $adminModel = new Admin();
                    $adminData = $adminModel->where('admin_id',$id)->find();
                    if ($adminData!=null){
                        if ($adminData['username']!='admin'){
                            $res = $adminModel->where('admin_id',$id)->delete();
                            if ($res){
                                return $this->resMessage(1,'删除成功！');
                            }else{
                                return $this->resMessage(0,'删除失败！');
                            }
                        }else{
                            return $this->resMessage(0,'admin为网站建设者不能删除！');
                        }

                    }else{
                        return $this->resMessage(0,'数据不存在！');
                    }

            }else{
                return $this->resMessage(0,'缺少参数！');
            }
        }else{
            abort(404);
        }
    }

    /**
     * 角色组列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function role()
    {
        $get = $_GET;
        unset($get['/admin/role/role_html']);
        $where=[];
        if (isset($get['role_name'])&&!empty($get['role_name'])){
            $where['role_name']=['like','%'.$get['role_name'].'%'];
        }
        $roleModel = new RoleMoel();
        $roleData = $roleModel->where($where)->paginate(15,false,['query'=>$get]);
        $this->assign('roleData', $roleData);
        return $this->fetch();
    }

    /**
     * 角色组添加功能
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function roleadd()
    {
        if (\request()->isGet()) {
            return $this->fetch();
        }
        if (\request()->isAjax()) {
            $post = input('post.');
            $validate = validate('Role');
            if (!$validate->scene('add')->check($post)) {
                return $this->resMessage(0,$validate->getError());
            }
            $roleModel = new RoleMoel();
            $oldData = $roleModel->where('role_name',$post['role_name'])->find();
            if ($oldData!=null){
                return $this->resMessage(0,'角色组已经存在');
            }
            $data=[
                'role_name'=>$post['role_name'],
                'create_time'=>time(),
                'describe'=>$post['describe'],
            ];

            $res = $roleModel->save($data);
            if ($res){
               return $this->resMessage(1,'添加成功！');
            }else{
                return $this->resMessage(0,'添加失败！');
            }

        }

    }

    /**
     * 角色删除操作
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function roledel(){
        if (\request()->isAjax()){
            if (input('?post.id')){
                $id = input('post.id');
                $roleModel =new RoleMoel();
                $oldData = $roleModel->where('role_id',$id)->find();
                if ($oldData!=null){
                    $adminModel = new Admin();
                    $adminData = $adminModel->where('role_id',$id)->find();
                    if ($adminData==null){
                        $res = $roleModel->where('role_id',$id)->delete();
                        if ($res){
                            return $this->resMessage(1,'删除成功！');
                        }else{
                            return $this->resMessage(0,'删除失败！');
                        }
                    }else{
                        return $this->resMessage(0,'当前角色组正在使用！');
                    }
                }else{
                    return $this->resMessage(0,'数据不存在！');
                }
            }else{
                return $this->resMessage(0,'缺少参数！');
            }
        }else{
            abort(404);
        }
    }

    /**
     * 载入修改页面和修改数据操作
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function roleedit(){
        $roleModel = new RoleMoel();
//        加载页面
        if (\request()->isGet()){
            if (input('?param.id')){
                $id = input('param.id');

                $olddata= $roleModel->where('role_id',$id)->find();
                if ($olddata!=null){
                    $this->assign('roleData',$olddata);
                    return $this->fetch();
                }else{
                    abort(404);
                }

            }else{
                abort(404);
            }
        }
//        修改数据
        if (\request()->isAjax()){
            $post = input('post.');
            $validate = validate('Role');
            if (!$validate->scene('edit')->check($post)){
                return $this->resMessage(0,$validate->getError());
            }
            $id = $post['id'];
            $oldData = $roleModel->where('role_id',$id)->find();
            if ($oldData!=null){
                $data = [
                    'role_name'=>$post['role_name'],
                    'describe'=>$post['describe'],
                ];
                $res = $roleModel->save($data,['role_id'=>$id]);
                if ($res){
                    return $this->resMessage(1,'修改成功');
                }else{
                    return $this->resMessage(0,'修改失败');
                }
            }else{
                return $this->resMessage(0,'出错了');
            }

        }


    }

    /**
     * 更改角色组状态
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function uprolesta(){
        if (\request()->isAjax()){
            if (input('?post.id')&&input('?post.sta')){
                $id = input('post.id');
                $sta = input('post.sta');
                $roleModle = new RoleMoel();
                $oldData = $roleModle->where('role_id',$id)->find();
                if ($oldData!=null){
                    $data = ['status'=>!$sta];
                    $res = $roleModle->save($data,['role_id'=>$id]);
                    if ($res){
                        return $this->resMessage(1,'修改成功！');
                    }else{
                        return $this->resMessage(0,'修改失败！');
                    }
                }else{
                    return $this->resMessage(0,'出错了！');
                }
            }else{
                return $this->resMessage(0,'缺少参数！');
            }
        }else{
            abort(404);
        }
    }

    /**
     * 显示数字结构
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function node()
    {
        $nodeModel = new Node();
        $data = $nodeModel->order('sort desc')->select();
        if ($data!=null){
            $data = collection($data)->toArray();
        }
        $tree = new Tree();
        $newData = $tree::tree($data,'node_title','node_id');
        $this->assign('nodeData',$newData);
        return $this->fetch();
    }


    /**添加节点
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function nodeadd(){
        if (\request()->isGet()){
            if (input('?param.pid')){
                $this->assign('pid',input('param.pid'));
            }
            return $this->fetch();
        }
        if (\request()->isAjax()){
            $post = input('post.');
            $validate = validate('Node');
            if (!$validate->check($post)){
                return $this->resMessage(0,$validate->getError());
            }
            $nodeModel = new Node();
            $nodeData = $nodeModel->where('node_title',$post['node_title'])->find();
            if ($nodeData!=null){
                return $this->resMessage(0,'规则名字已经存在');
            }
            if (!empty($post['node_name'])){
                $nodeData2 = $nodeModel->where('node_name',$post['node_name'])->find();
                if ($nodeData2!=null){
                    return $this->resMessage(0,'规则已经存在');
                }
            }

            $data= [
                'node_name'=>$post['node_name'],
                'node_title'=>$post['node_title'],
                'describe'=>$post['describe'],
                'type'=>$post['type'],
                'sort'=>$post['sort'],
                'create_time'=>time(),
                'icon'=>$post['icon']
            ];
            if (isset($post['pid'])){
                $data['pid']=$post['pid'];
            }
            if (isset($post['is_auth'])&&$post['is_auth']=='on'){
                $data['is_auth']=1;
            }else{
                $data['is_auth']=0;
            }
            $res = $nodeModel->save($data);
            if ($res){
                return $this->resMessage(1,'添加成功');
            }else{
                return $this->resMessage(0,'添加失败');
            }
        }

    }

    /**
     * 规则编辑操作
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function editnode(){
        $nodeModel = new Node();
        if (request()->isGet()){
            if (input('?param.id')){
                $id = input('param.id');
                $nodeData = $nodeModel->where('node_id',$id)->find();
                stripcslashes($nodeData['icon']);
                if ($nodeData!=null){
                    $this->assign('nodeData',$nodeData);
                    return $this->fetch();
                }else{
                    abort(404);
                }

            }else{
                abort(404);
            }

        }
        if (request()->isAjax()){
            $post = input('post.');
            if (isset($post['id'])){
                $id = $post['id'];
                $validate = validate('Node');
                if (!$validate->check($post)){
                    return $this->resMessage(0,$validate->getError());
                }
                $nodeData = $nodeModel->where('node_id',$id)->find();
                if ($nodeData!=null){
                    $data= [
                        'node_name'=>$post['node_name'],
                        'node_title'=>$post['node_title'],
                        'describe'=>$post['describe'],
                        'type'=>$post['type'],
                        'sort'=>$post['sort'],
                    ];
                    if (!empty($post['icon'])){
                        $data['icon']=$post['icon'];
                    }
                    if (isset($post['is_auth'])&&$post['is_auth']=='on'){
                        $data['is_auth']=1;
                    }else{
                        $data['is_auth']=0;
                    }
                    $res = $nodeModel->save($data,['node_id'=>$id]);
                    if ($res){
                        return $this->resMessage(1,'修改成功');
                    }else{
                        return $this->resMessage(0,'修改失败');
                    }
                }else{
                    return $this->resMessage(0,'数据不存在');
                }

            }else{
                return $this->resMessage(0,'缺少参数');
            }

        }

    }

    /**
     * 删除节点
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function nodedel(){
        if (\request()->isAjax()){
            if (input('?post.id')){
                $id = input('post.id');
                $nodeModel =new Node();
                $oldData = $nodeModel->where('node_id',$id)->find();
                if ($oldData!=null){
                    $pidData = $nodeModel->where('pid',$id)->select();
                    if ($pidData==null){
                        $res = $nodeModel->where('node_id',$id)->delete();
                        if ($res){
                            return $this->resMessage(1,'操作成功！');
                        }else{
                            return $this->resMessage(0,'操作失败！');
                        }
                    }else{
                        return $this->resMessage(0,'当前节点还有子节点，请先删除子节点！');
                    }
                }else{
                    return $this->resMessage(0,'数据不存在！');
                }
            }else{
                return $this->resMessage(0,'缺少参数！');
            }
        }else{
            abort(404);
        }
    }

    /**
     * 更改节点状态
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function upnodesta(){
        if (input('?post.id')&&input('?post.sta')){
            $id = input('post.id');
            $sta = input('post.sta');
            $nodeModel = new Node();
            $oldData = $nodeModel->where('node_id',$id)->find();
            if ($oldData!=null){
                $arr=[$id];
                if ($sta==1){
                    $sonids = $this->getsonids($id,'node_id');
                    if ($sonids!=null){
                        foreach ($sonids as $v){
                            if (!in_array($v,$arr)){
                                array_push($arr,$v);
                            }
                        }
                    }
                }

                if ($oldData['pid']!=0){
                    $fatherids = $this->getfathrerids($id,'node_id');
                    if ($fatherids!=null){
                        foreach ($fatherids as $v){
                            if (!in_array($v,$arr)){
                                array_push($arr,$v);
                            }
                        }
                    }
                }

                $where['node_id']=['in',$arr];
                $data = ['status'=>!$sta];
                $res = $nodeModel->where($where)->update($data);

                if ($res){
                    return $this->resMessage(1,'修改成功！');
                }else{
                    return $this->resMessage(0,'修改失败！');
                }
            }else{
                return $this->resMessage(0,'出错了！');
            }
        }else{
            return $this->resMessage(0,'缺少参数！');
        }
    }

    /**
     * 角色授权
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function uprole()
    {
        $roleModel = new RoleMoel();
        if (request()->isGet()){
            if (input('?param.id')){
                $id =input('param.id');
                $nodeData = $roleModel->where('role_id',$id)->field('nodes')->find()->toArray();
                $nodes = explode(',',$nodeData['nodes']);
                $this->assign('nodes',$nodes);
                $this->assign('id',$id);
                $nodeModel = new Node();
                $data = $nodeModel->where('is_auth',1)->select();
                if ($data!=null){
                    $data = collection($data)->toArray();
                }
                $nodeData = getTreeData($data,'pid','node_id');
                $this->assign('nodeData',$nodeData);
                return $this->fetch();
            }else{
                abort(404);
            }

        }
        if (\request()->isAjax()){
            $post = input('post.');
            if (isset($post['id'])&&!empty($post['id'])){
                $id = $post['id'];
                if (isset($post['nodeids'])&&!empty($post['nodeids'])){
                    $ids = $post['nodeids'];
                    $nodeids = implode(',',$ids);

                    $res = $roleModel->save(['nodes'=>$nodeids],['role_id'=>$id]);
                    if ($res){
                        return $this->resMessage(1,'授权成功');
                    }else{
                        return $this->resMessage(0,'授权失败');
                    }
                }else{
                    return $this->resMessage(0,'请选择节点');
                }
            }else{
                return $this->resMessage(0,'缺少参数');
            }
        }

    }
}
